#include "StdAfx.h"
#include "IContourFind.h"
//OpenCV libs
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"

const char * const IContourFind::FunctionNameIContourFind = "Contour - Find";

IContourFind::IContourFind(void) 
{
	_fnApi.SetFunctionName(IContourFind::FunctionNameIContourFind);
	_fnApi.SetFunctionDescription("Finds the contours in a image");
									//inputs
	_fnApi.AddParamDef(new ProcParamDefString(0, "NULL", "NULL", ProcParamDef::input, 0, 500 ));
									//outputs
	_fnApi.AddParamDef(new ProcParamDefInt(0, ProcParam::attribOutputParamNameResult, "0 is success", ProcParamDef::output, 0, 1));

	_fnApi.Validate();
}


IContourFind::~IContourFind(void)
{

}


bool IContourFind::Process(ImageProcStep *step, bool DebugMode)
{	
	bool rc = false;
	if ((step != '\0') && (step->IsValid()))
	{
		cv::Mat input = cv::imread(step->GetIntermediateImagePathFilename());

		//Prepare the image for findContours
		cv::cvtColor(input, input, CV_BGR2GRAY);
		cv::threshold(input, input, 128, 255, CV_THRESH_BINARY);

		//Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten
		std::vector<std::vector<cv::Point> > contours;
		cv::Mat contourOutput = input.clone();
		cv::findContours( contourOutput, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE );

		//Draw the contours
		cv::Mat contourImage(input.size(), CV_8UC3, cv::Scalar(0,0,0));
		cv::Scalar colors[3];
		colors[0] = cv::Scalar(255, 0, 0);
		colors[1] = cv::Scalar(0, 255, 0);
		colors[2] = cv::Scalar(0, 0, 255);
		for (size_t idx = 0; idx < contours.size(); idx++)
		{
			cv::drawContours(contourImage, contours, idx, colors[idx % 3]);
		}
	
			

		cv::imwrite(step->GetIntermediateImagePathFilename(), contourImage);

		input.release();
		contourImage.release();
		//result->SetValue(0);
		rc = true;

	}
	return rc;
}
